package org.example.backend.controller;

import org.example.backend.common.Result;
import org.example.backend.entity.Users;
import org.example.backend.mapper.UsersMapper;
import org.example.backend.util.BCryptUtils;
import org.example.backend.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class UsersController {

    private static final String AUTH_COOKIE_NAME = "LINZEYO_AUTH";

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private TokenUtil tokenUtil;

    @PostMapping("/register")
    public Result<Map<String, Object>> register(String username, String password, String email) {
        if (usersMapper.searchAllByUsernameAndEmail(username, email).isEmpty()) {
            Users user = new Users();
            user.setUsername(username);
            String hashed = BCryptUtils.hash(password);
            user.setPassword_hash(hashed);
            user.setEmail(email);
            user.setRole("user"); // 设置默认角色
            usersMapper.insert(user);

            // 构建响应数据
            Map<String, Object> data = new HashMap<>();
            data.put("userId", user.getId());
            data.put("username", user.getUsername());
            data.put("expiresIn", 3600);

            return Result.success("注册成功", data);
        } else {
            return Result.error("用户名或邮箱已存在");
        }
    }

    @PostMapping("/login")
    public ResponseEntity<Result<Map<String, Object>>> login(String username, String password) {
        Users user = usersMapper.searchAllByUsername(username);
        if (user == null) {
            return ResponseEntity.ok(Result.error("用户不存在"));
        }
        if (!BCryptUtils.verify(password, user.getPassword_hash())) {
            return ResponseEntity.ok(Result.error("密码错误"));
        }

        // 生成JWT token
        String token = tokenUtil.generateToken(user.getUsername());

        // 创建JWT cookie - 开发环境配置
        ResponseCookie jwtCookie = ResponseCookie.from(AUTH_COOKIE_NAME, token)
                .httpOnly(true)         // 防止JavaScript访问
                .secure(false)          // 在开发环境中关闭secure要求
//                .maxAge(24 * 60 * 60)   // 24小时有效期（秒）
                .maxAge(10 * 60)   // 10分钟有效期（秒）（测试期）
                .path("/")              // 在整个应用中可用
                .sameSite("Lax")        // 开发环境使用较宽松的同站策略
                .build();

        // 构建响应数据
        Map<String, Object> data = new HashMap<>();
        data.put("userId", user.getId());
        data.put("username", user.getUsername());
        data.put("avatarUrl", user.getAvatar_url());
        data.put("role", user.getRole());
        data.put("token", token);
        data.put("expiresIn", 3600);

        // 返回带有cookie的响应
        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
                .body(Result.success("登录成功", data));
    }

    @GetMapping("/resource")
    public Result<String> getResource() {
        return Result.success("获取资源成功");
    }

    @PostMapping("/logout")
    public ResponseEntity<Result<String>> logout() {
        // 创建过期的cookie来删除现有cookie
        ResponseCookie jwtCookie = ResponseCookie.from(AUTH_COOKIE_NAME, "")
                .httpOnly(true)
                .secure(false)
                .maxAge(0)  // 立即过期
                .path("/")
                .sameSite("Lax")
                .build();

        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
                .body(Result.success("退出登录成功"));
    }

    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @GetMapping("/me")
    public Result<Map<String, Object>> getUserInfo(
            @RequestHeader(value = "token", required = false) String headerToken,
            @CookieValue(value = "LINZEYO_AUTH", required = false) String cookieToken) {
        try {
            // 优先使用请求头中的token，如果没有则使用cookie中的token
            String token = headerToken;
            if (!StringUtils.hasLength(token) && StringUtils.hasLength(cookieToken)) {
                token = cookieToken;
            }

            if (!StringUtils.hasLength(token)) {
                return Result.unauthorized("未登录");
            }

            // 从token中提取用户名
            String username = tokenUtil.extractUsername(token);

            // 检查token是否过期
            if (tokenUtil.extractExpiration(token).before(new java.util.Date())) {
                return Result.unauthorized("登录已过期");
            }

            // 通过用户名获取用户信息
            Users user = usersMapper.searchAllByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }


            //TODO: 计算用户收藏和上传数量
            // 获取用户的收藏数量和上传数量（需要实现这些方法或调用相应服务）
            int favoriteCount = 0; // 替换为实际获取方法
            int uploadCount = 0;   // 替换为实际获取方法

            // 构建响应数据
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("email", user.getEmail());
            data.put("avatarUrl", user.getAvatar_url());
            data.put("role", user.getRole());
            data.put("registeredAt", user.getCreated_at());
            data.put("favoriteCount", favoriteCount);
            data.put("uploadCount", uploadCount);

            return Result.success("获取用户信息成功", data);
        } catch (Exception e) {
            return Result.unauthorized("token解析失败: " + e.getMessage());
        }
    }
}